package com.zkh.myutils.net.utils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.SecureRandom;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

import com.zkh.myutils.net.DefaultHostnameVerifier;
import com.zkh.myutils.net.DefaultX509TrustManager;
import com.zkh.myutils.utils.UtilsException;

/**
 * Net工具类
 * @author zkh
 */
public class NetUtils {
	
	/**
	 * 复制流数据
	 * @param source 原流
	 * @param dest 目标流
	 * @param bufferSize 缓冲大小，大于-1时生效
	 */
	public static long copyStream(InputStream source, OutputStream dest, int bufferSize) throws IOException {
		//处理流
		int bytes;
		byte[] buffer = new byte[bufferSize > 0 ? bufferSize : 1024];
		long size = 0;
		//写入数据
		while ((bytes = source.read(buffer)) != -1) {
			//结束
			if (bytes == 0) {
				//读取下一行
				bytes = source.read();
				//没有数据，退出
				if (bytes < 0) break;
				//写入数据
				dest.write(bytes);
				dest.flush();
				//累加
				++size;
				continue;
			}
			//写数据
			dest.write(buffer, 0, bytes);
			dest.flush();
			size += bytes;
		}
		//返回
		return size;
	}
	
	/**
	 * 获取默认SSL Socket工厂
	 * @return
	 */
	public static SSLSocketFactory getSSLDefaultSocketFactory() {
		//SSL Context对象
		SSLContext context = null;
		try {
			//获取一个SSL实例
			context = SSLContext.getInstance("SSL");
			//默认SSL管理器列表
			TrustManager[] trustManagers = {new DefaultX509TrustManager()};
			//使用默认SSL管理器初始化
	        context.init(null, trustManagers, new SecureRandom());
		}catch (Exception e) {
			//获取SSL实体失败
			throw new UtilsException(e);
		}
		//返回一个SSLSocket工厂
        return context.getSocketFactory();
	}
	
	/**
	 * 获取默认空域名验证器
	 * @return
	 */
	public static DefaultHostnameVerifier getDefaultHostnameVerifier() {
		return new DefaultHostnameVerifier();
	}
}
